<template>
  <Drawer
    placement="right"
    :closable="true"
    v-model="visible"
    width="400"
    scrollable
    @on-close="cancel"
  >
    <template #header>
      <div class="flex flex-col justify-between">
        <div class="flex items-center mb-4 gap-x-2">
          <img
            src="~@/assets/images/icon_DatabaseUpdate.jpg"
            class="w-6 h-6 rounded"
            alt="Start icon"
          />
          <div class="flex flex-col gap-y-1">
            <p class="text-lg font-semibold text-black">{{ title }}</p>
          </div>
        </div>
        <div class="text-sm text-gray-500">
          修改表中已存在的数据记录，用户指定更新条件和内容来更新数据
        </div>
      </div>
    </template>
    <CommonCollapse title="数据表">
      <template #right>
        <Button
          v-show="!selectSQL.name"
          type="primary"
          size="small"
          icon="md-add"
          @click="addSQL()"
        ></Button>
      </template>
      <div class="text-center text-gray-400" v-show="!selectSQL.name">
        <Icon type="md-cube" size="30" />
        <p class="mt-2 text-xs">请添加数据表到此节点，仅支持添加一个数据表</p>
      </div>
      <div v-show="selectSQL.name">
        <div
          class="flex items-center justify-between p-3 mb-2 border border-gray-200 border-solid rounded-md border-1 bg-slate-50"
        >
          <div class="flex items-center flex-1">
            <img
              class="w-8 h-8 rounded"
              src="~@/assets/images/database_default.png"
              alt="database default"
            />
            <p class="flex-1 ml-3">{{ selectSQL.name }}</p>
          </div>
          <Icon
            type="ios-trash"
            size="20"
            class="cursor-pointer"
            @click="handleSQLRemove"
          />
        </div>
        <div class="flex flex-wrap items-center mt-3" v-if="selectSQL.sqlList?.length">
          <div
            class="mb-2 cursor-pointer text-bg-normal"
            style="font-size: 14px"
            v-for="(item, i) in selectSQL.sqlList"
            :key="i"
            v-show="i < 3 || showLeave"
            @click="copyText(item.fieldname)"
          >
            {{ item.fieldname }}
          </div>
          <div
            class="mb-2 cursor-pointer text-bg-normal"
            style="font-size: 14px"
            v-show="!showLeave"
            @click="showLeave = true"
          >
            +{{ selectSQL?.sqlList.length - 3 }}
          </div>
          <div
            class="mb-2 cursor-pointer text-bg-normal"
            style="font-size: 14px"
            v-show="showLeave"
            @click="showLeave = false"
          >
            <Icon type="ios-arrow-up" size="20" />
          </div>
        </div>
      </div>
    </CommonCollapse>
    <Divider v-if="selectSQL.name"></Divider>
    <CommonCollapse title="更新条件" v-if="selectSQL.name">
      <CommonConditionModule :form="form.selectlist[0]"  :sqlList="selectSQL.sqlList" />
    </CommonCollapse>
    <Divider v-if="selectSQL.name"></Divider>
    <CommonCollapse title="选择并设置字段" v-if="selectSQL.name">
      <template #right>
        <Dropdown trigger="click">
          <Button type="primary" size="small" icon="md-add" :disabled="filterSettingList.length == 0"></Button>
          <template #list v-if="filterSettingList.length">
            <DropdownMenu>
              <DropdownItem
                v-for="(item, i) in filterSettingList"
                :key="i"
                @click.stop="addSetting(item)"
              >
                <span>{{ item.fieldname }}</span>
                <span
                  class="py-1 ml-2 text-xs truncate rounded bg-slate-100"
                  style="max-width: 80px"
                >
                  {{ item.vartype }}
                </span></DropdownItem
              >
            </DropdownMenu>
          </template>
        </Dropdown>
      </template>
      <div class="panel-table">
        <div class="panel-table-header">
          <div class="name" style="width: 150px">变量名</div>
          <div class="name">变量值</div>
        </div>
        <div class="panel-table-list">
          <Form ref="formEl" :model="form" label-position="top">
            <div
              class="flex items-center"
              v-for="(item, index) in form.inoutlist"
              :key="index"
            >
              <div class="flex items-center" style="width: 160px">
                <div class="text-sm">{{ item.varname }} <span class="text-red-500" v-if="item.required">*</span></div>
                <Tooltip transfer theme="light" placement="top" :content="item.description" v-if="item.description">
                  <Icon type="ios-alert-outline" size="14" />
                </Tooltip>
                <div
                  class="px-2 ml-2 text-xs truncate rounded bg-slate-100"
                >
                  {{ item.vartype }}
                </div>
              </div>
              <div class="panel-table-item" style="width: 180px">
                <!-- <FormItem
                  :prop="'inoutlist.' + index + '.value'"
                  :rules="{
                    required: item.required,
                    message: '变量值不可为空',
                    trigger: 'blur',
                  }"
                > -->
                  <Input
                    size="small"
                    v-model="item.varparam"
                    check-strictly
                    placeholder="输入参数值"
                  >
                  </Input>
                <!-- </FormItem> -->
              </div>
              <div
                class="panel-table-item btn"
                @click="removeInput('inoutlist', index)"
              >
                <Icon type="md-remove" />
              </div>
            </div>
          </Form>
        </div>
      </div>
    </CommonCollapse>
    <Divider></Divider>
    <CommonCollapse
      title="输出"
      tip="批处理完成后输出的内容，仅支持引用批处理体中节点的输出变量"
    >
      <CommonOutputModule
        :data="form.outputjsonlist"
        @add="addInput('outputjsonlist')"
        @remove="removeInput('outputjsonlist', $event)"
      />
    </CommonCollapse>
    <Divider></Divider>
    <CommonCollapse
      title="异常处理"
      tip="可设置异常处理，包括超时、重试、异常处理方式。"
    >
      <CommonAbnormalModule :form="form.excepjsondata" />
    </CommonCollapse>
  </Drawer>
  <SQLSelectModule ref="selectRef" @select="handleSQLSelect" />
</template>
<script setup>
import { ref, computed } from 'vue';
import CommonCollapse from '@/components/CommonCollapse/index.vue';
import SQLSelectModule from '../dialog/SQLSelect.vue';
import CommonOutputModule from './common-output-module.vue';
import CommonConditionModule from './common-condition-module.vue';
import CommonAbnormalModule from './common-abnormal-module.vue';

import { Modal } from 'view-ui-plus';

import { copyText } from '@/util/index';

const props = defineProps({
  form: {
    type: Object,
    default: () => {},
  },
  title: {
    type: String,
    default: 'SQL自定义',
  },
  selectSQL: {
    type: Object,
    default: () => {},
  }
});

const emit = defineEmits(['add', 'remove', 'cancel']);

const visible = ref(false);
// 展开数据表剩下字段
const showLeave = ref(false);

// 选择设置字段数据
const filterSettingList = computed(() => {
  // const list = props.selectSQL.sqlList.slice(4);

  const list = props.selectSQL.sqlList;
  return list.filter(item => {
    const index = props.form.inoutlist.findIndex(j => j.varname == item.fieldname);
    return index < 0;
  })
});

// 组件的增删
const addInput = (listKey) => {
  emit('add', listKey);
};
const removeInput = (listKey, index) => {
  emit('remove', listKey, index);
};

const addSetting = (item) => {
  props.form.inoutlist.push({
    varname: item.fieldname,
    vartype: item.vartype || 'String',
    varparam: '',
  })
}

const selectRef = ref(null);
const addSQL = () => {
  selectRef.value?.init();
};

const handleSQLSelect = (sql, info) => {
  props.form.databeseid = sql.id;
  props.selectSQL.name = sql.name;
  props.selectSQL.sqlList = info;
};
const handleSQLRemove = () => {
  Modal.confirm({
    mask: false,
    title: '确认移除该数据表？',
    content: `<p>移除后，该节点配置的相关内容均会被删除且无法恢复</p>`,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      props.selectSQL.name = '';
      props.selectSQL.sqlList = [];
      props.form.databeseid = '';
      props.form.inoutlist = [];
      props.form.selectlist =  [
        {
          andor: 'and',
          publicjson: []
        }
      ];
    },
  });
};

const init = () => {
  visible.value = true;
};
const cancel = () => {
  visible.value = false;
  emit('cancel')
};

defineExpose({
  init,
});
</script>
<style lang="scss">
.panel-table-header {
  align-items: center;
  display: flex;
  gap: 4px;
  padding: 0 4px;

  .name {
    width: 120px;
    margin-right: 6px;
    box-sizing: content-box;
  }
  .center {
    text-align: center;
  }
}

:deep(.ivu-form-item-error-tip){
  font-size: 12px;
}
.panel-table-item {
  height: 30px;
  margin-right: 6px;
  &.center {
    text-align: center;
  }
  &.btn {
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    margin-left: 12px;
    height: 22px;
  }
}

.condition-logic{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 50px;
  height: auto;

  .left,.right {
    border: 1px solid rgb(68 83 130 / 25%);
    width: 50%;
    height: calc(50% - 47px);
    translate: 50%;
  }
  .left {
    border-right: 0;
    border-bottom: 0;
    border-top-left-radius: 6px;
  }
  .right {
    border-right: 0;
    border-top: 0;
    border-bottom-left-radius: 6px;
  }
}
</style>
